//导入模板文件

import usersTpl from '../../views/users.art';
import usersListTpl from '../../views/users-list.art';
import pagination from '../../components/pagination';
import page from '../../databus/page';
import {
  addUser
} from './add-user';
import {
  usersListModel
} from '../../models/users-list';
import {
  authModel
} from '../../models/auth';
import {
  remove
} from '../common/index';



const pageSize = page.pageSize;

//数据
let state = {
  list: []
};
// let dataList = [];

//订阅模式
const _subscribe = () => {
  $('body').on('changeCurrentPage', (e, index) => {
    _list(index);
  });
  $('body').on('addUser', (e) => {
    _loadData();
  });
}

//请求用户列表数据 传入页码数字
const _list = (pageNo) => {
  $('#users-list').html(usersListTpl({
    //渲染部分数据 数据截取slice(从何处开始选取, 数组下标开始选取个数)
    //第一页 -> 0-10 -> ((1 - 1) * 10, 1 * 10)
    //第二页 -> 10-20 -> ((2 - 1) * 10, 2 * 10)
    data: state.list.slice((pageNo - 1) * pageSize, pageNo * pageSize)
  }));
}

//请求数据库数据并存入临时数据dataList 并渲染数据
const _loadData = async () => {
  let result = await usersListModel();
  state.list = result.data;
  //实现分页 此处应该放公共参数
  pagination(result.data, pageSize, page.currentPage);
  //数据渲染
  _list(page.currentPage);
}

//首页
const index = (router) => {

  const loadIndex = async (res, next) => {
    next();
    res.render(usersTpl());
    //触发添加用户按钮
    $('#add-user-btn').on('click', addUser);
    //获取用户列表数据
    await _loadData();
    //页面事件绑定
    remove({
      $box: $('#users-list'),
      state, //传递一个引用类型的值stata
      // dataList,
      url: 'api/users',
      loadData: _loadData
    });
    //订阅事件
    _subscribe();
  }

  return async (req, res, next) => {
    let result = await authModel();
    if (result.ret) {
      loadIndex(res, next)
    } else {
      router.go('/signin');
    }
  };
};


export default index